package cn.thoughtworks.school.services;


import cn.thoughtworks.school.entities.Stack;
import cn.thoughtworks.school.entities.User;
import cn.thoughtworks.school.handlers.BusinessException;
import cn.thoughtworks.school.repositories.StackRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class StackService {
    @Autowired
    private StackRepository stackRepository;
    @Autowired
    private UserCenterService userCenterService;
    @Autowired
    private Utils utils;

    public Stack addStack(Map data, User current){
      Long organizationId = userCenterService.getUserCurrentOrganizationId(current.getId());
      String image = (String) data.get("image");
      String description = (String) data.get("description");

      Stack stack = new Stack(description,image,current.getId(),image,organizationId);
      return stackRepository.save(stack);
    }


    public Stack getStack(Long id) throws BusinessException{
        return stackRepository.findById(id).orElseThrow(()->{
            String message = String.format("stack is not exist with id: %s", id);
            return new BusinessException(message);
        });
    }

    public List<Stack> findStacksByOrganization(User current) {
        Long organizationId = userCenterService.getUserCurrentOrganizationId(current.getId());
        return stackRepository.findAllByOrganizationId(organizationId);
    }

    public Page<Stack> findStackPageableByOrganization(User current, Pageable pageable) {
        Long organizationId = userCenterService.getUserCurrentOrganizationId(current.getId());
        Page stacksPage = stackRepository.findAllByOrganizationId(organizationId,pageable);
        return utils.format(stacksPage, pageable);
    }

    public Stack findStackByImageAndOrganization(String image, User current) {
        Long organizationId = userCenterService.getUserCurrentOrganizationId(current.getId());
        return stackRepository.findStackByImageAndOrganizationId(image,organizationId);
    }
}
